package com.example.studentknowledge.controller;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Category;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.entity.PointRecord;
import com.example.studentknowledge.service.ArticleService;
import com.example.studentknowledge.service.CategoryService;
import com.example.studentknowledge.service.UserService;
import com.example.studentknowledge.service.PointService;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.io.UnsupportedEncodingException;

/**
 * 主页控制器
 */
@Controller
public class HomeController {
    
    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PointService pointService;
    
    /**
     * 首页
     */
    @GetMapping("/")
    public String home(Model model, 
                      @RequestParam(defaultValue = "0") int page,
                      @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            model.addAttribute("articles", articleService.getPublishedArticles(pageable));
            model.addAttribute("categories", categoryService.findAllEnabled());
            return "articles";  // 改为 articles 显示文章列表
        } catch (Exception e) {
            // 如果服务出错，返回简单的欢迎页面
            model.addAttribute("message", "欢迎使用学生知识管理系统");
            return "welcome";
        }
    }
    
    /**
     * 关于页面
     */
    @GetMapping("/about")
    public String about() {
        return "about";
    }
    
    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    
    /**
     * 注册页面
     */
    @GetMapping("/register")
    public String register() {
        return "register";
    }
    
    /**
     * 个人资料页面
     */
    @GetMapping("/profile")
    public String profile(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            model.addAttribute("user", user);
            // 添加统计数据
            model.addAttribute("articleCount", articleService.countUserArticles(user));
            model.addAttribute("favoriteCount", 0); // TODO: 实现收藏统计
            model.addAttribute("followCount", 0); // TODO: 实现关注统计
            
            return "profile";
        } catch (Exception e) {
            model.addAttribute("error", "获取用户信息失败：" + e.getMessage());
            return "redirect:/";
        }
    }
    
    /**
     * 头像管理页面
     */
    @GetMapping("/profile/avatar")
    public String avatarManagement(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            model.addAttribute("user", user);
            return "profile-avatar";
        } catch (Exception e) {
            model.addAttribute("error", "获取用户信息失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }
    
    /**
     * 积分管理页面
     */
    @GetMapping("/profile/points")
    public String pointsManagement(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 获取积分记录
            Page<PointRecord> pointRecordsPage = pointService.getUserPointRecords(user, PageRequest.of(0, 20));
            List<PointRecord> pointRecords = pointRecordsPage.getContent();
            
            model.addAttribute("user", user);
            model.addAttribute("pointRecords", pointRecords);
            return "profile-points";
        } catch (Exception e) {
            model.addAttribute("error", "获取积分信息失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }
    
    /**
     * 我的文章页面
     */
    @GetMapping("/profile/articles")
    public String myArticles(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 获取用户的文章
            Page<Article> articlesPage = articleService.getArticlesByAuthor(user, PageRequest.of(0, 20));
            List<Article> articles = articlesPage.getContent();
            
            model.addAttribute("user", user);
            model.addAttribute("articles", articles);
            return "profile-articles";
        } catch (Exception e) {
            model.addAttribute("error", "获取文章列表失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }
    
    /**
     * 我的收藏页面
     */
    @GetMapping("/profile/favorites")
    public String myFavorites(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            model.addAttribute("user", user);
            // TODO: 实现收藏功能后添加收藏列表
            model.addAttribute("favorites", new ArrayList<>());
            return "profile-favorites";
        } catch (Exception e) {
            model.addAttribute("error", "获取收藏列表失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }
    
    /**
     * 我的关注页面
     */
    @GetMapping("/profile/follows")
    public String myFollows(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            model.addAttribute("user", user);
            // TODO: 实现关注功能后添加关注列表
            model.addAttribute("follows", new ArrayList<>());
            return "profile-follows";
        } catch (Exception e) {
            model.addAttribute("error", "获取关注列表失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }
    
    /**
     * 消息中心页面
     */
    @GetMapping("/profile/messages")
    public String messageCenter(Model model, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return "redirect:/login";
        }
        
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            model.addAttribute("user", user);
            // TODO: 实现消息功能后添加消息列表
            model.addAttribute("messages", new ArrayList<>());
            return "profile-messages";
        } catch (Exception e) {
            model.addAttribute("error", "获取消息列表失败：" + e.getMessage());
            return "redirect:/profile";
        }
    }

    /**
     * 更新个人资料
     */
    @PostMapping("/profile/update")
    public String updateProfile(@ModelAttribute User userInfo, Authentication authentication, Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> currentUserOpt = userService.findByUsername(username);
        if (!currentUserOpt.isPresent()) {
            return "redirect:/login";
        }
        User currentUser = currentUserOpt.get();
        
        if (currentUser != null) {
            // 更新用户信息
            if (userInfo.getNickname() != null && !userInfo.getNickname().trim().isEmpty()) {
                currentUser.setNickname(userInfo.getNickname());
            }
            if (userInfo.getEmail() != null && !userInfo.getEmail().trim().isEmpty()) {
                currentUser.setEmail(userInfo.getEmail());
            }
            if (userInfo.getRealName() != null && !userInfo.getRealName().trim().isEmpty()) {
                currentUser.setRealName(userInfo.getRealName());
            }
            if (userInfo.getPhone() != null && !userInfo.getPhone().trim().isEmpty()) {
                currentUser.setPhone(userInfo.getPhone());
            }
            if (userInfo.getBio() != null && !userInfo.getBio().trim().isEmpty()) {
                currentUser.setBio(userInfo.getBio());
            }
            
            userService.updateUser(currentUser);
            model.addAttribute("message", "个人信息更新成功！");
        }
        
        return "redirect:/profile";
    }
    
    @GetMapping("/articles")
    public String articles(@RequestParam(defaultValue = "0") int page,
                          @RequestParam(defaultValue = "10") int size,
                          @RequestParam(required = false) String status,
                          @RequestParam(required = false) Long categoryId,
                          @RequestParam(required = false) String keyword,
                          Authentication authentication,
                          Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        // 获取所有已发布的文章列表（如果没有指定状态筛选）
        Pageable pageable = PageRequest.of(page, size);
        Page<Article> articles;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有关键词搜索，使用搜索方法
            articles = articleService.searchArticles(keyword.trim(), pageable);
        } else if (categoryId != null) {
            // 如果指定了分类，按分类获取文章
            articles = articleService.getArticlesByCategory(categoryId, pageable);
        } else {
            // 获取所有文章（包括草稿和已发布的）
            articles = articleService.getAllArticles(pageable);
        }
        
        model.addAttribute("articles", articles);
        
        // 获取分类列表
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        
        return "articles";
    }
    
    @GetMapping("/articles/create")
    public String createArticle(Authentication authentication, Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        // 获取分类列表
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        
        return "article-edit";
    }
    
    @PostMapping("/articles/create")
    public String createArticle(@RequestParam String title,
                               @RequestParam Long categoryId,
                               @RequestParam String status,
                               @RequestParam(required = false) String summary,
                               @RequestParam String content,
                               Authentication authentication,
                               Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            return "redirect:/login";
        }
        User user = userOpt.get();
        
        if (user != null) {
            try {
                Article article = new Article();
                article.setTitle(title);
                article.setSummary(summary);
                article.setContent(content);
                article.setAuthor(user);
                
                // 设置分类
                Category category = categoryService.getCategoryById(categoryId);
                article.setCategory(category);
                
                // 设置状态
                if ("PUBLISHED".equals(status)) {
                    article.setStatus(Article.Status.PUBLISHED);
                } else {
                    article.setStatus(Article.Status.DRAFT);
                }
                
                Article savedArticle = articleService.createArticle(article);
                
                // 如果是发布状态，给用户奖励积分
                if ("PUBLISHED".equals(status)) {
                    try {
                        pointService.addPoints(user, 10, PointRecord.PointType.ARTICLE_CREATE, "发布文章");
                    } catch (Exception e) {
                        // 积分奖励失败不影响文章发布
                    }
                }
                
                try {
                    return "redirect:/articles?success=true&message=" + 
                           java.net.URLEncoder.encode("文章" + ("PUBLISHED".equals(status) ? "发布" : "保存") + "成功！", "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    return "redirect:/articles?success=true";
                }
            } catch (Exception e) {
                model.addAttribute("error", "文章创建失败：" + e.getMessage());
                List<Category> categories = categoryService.getAllCategories();
                model.addAttribute("categories", categories);
                return "article-edit";
            }
        }
        
        return "redirect:/login";
    }
    
    @GetMapping("/articles/{id}/edit")
    public String editArticle(@PathVariable Long id, Authentication authentication, Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            return "redirect:/login";
        }
        User user = userOpt.get();
        
        Article article = articleService.getArticleById(id);
        if (article == null || !article.getAuthor().equals(user)) {
            return "redirect:/articles";
        }
        
        model.addAttribute("article", article);
        
        // 获取分类列表
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        
        return "article-edit";
    }
    
    @PostMapping("/articles/{id}/update")
    public String updateArticle(@PathVariable Long id,
                               @RequestParam String title,
                               @RequestParam Long categoryId,
                               @RequestParam String status,
                               @RequestParam(required = false) String summary,
                               @RequestParam String content,
                               Authentication authentication,
                               Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            return "redirect:/login";
        }
        User user = userOpt.get();
        
        Article article = articleService.getArticleById(id);
        if (article == null || !article.getAuthor().equals(user)) {
            return "redirect:/articles";
        }
        
        try {
            article.setTitle(title);
            article.setSummary(summary);
            article.setContent(content);
            
            // 设置分类
            Category category = categoryService.getCategoryById(categoryId);
            article.setCategory(category);
            
            // 设置状态
            if ("PUBLISHED".equals(status)) {
                article.setStatus(Article.Status.PUBLISHED);
            } else {
                article.setStatus(Article.Status.DRAFT);
            }
            
            articleService.updateArticle(article);
            model.addAttribute("message", "文章更新成功！");
            return "redirect:/articles";
        } catch (Exception e) {
            model.addAttribute("error", "文章更新失败：" + e.getMessage());
            model.addAttribute("article", article);
            List<Category> categories = categoryService.getAllCategories();
            model.addAttribute("categories", categories);
            return "article-edit";
        }
    }
    
    @GetMapping("/articles/{id}")
    public String viewArticle(@PathVariable Long id, Model model) {
        try {
            Article article = articleService.getArticleById(id);
            if (article == null || article.getStatus() != Article.Status.PUBLISHED) {
                return "redirect:/articles";
            }
            
            // 增加阅读量
            articleService.incrementViewCount(id);
            
            // 重新获取文章以获得更新后的阅读量
            article = articleService.getArticleById(id);
            model.addAttribute("article", article);
            
            return "article-detail";
        } catch (Exception e) {
            return "redirect:/articles";
        }
    }
    
    @GetMapping("/admin/articles")
    public String adminArticles(Authentication authentication, Model model,
                               @RequestParam(defaultValue = "0") int page,
                               @RequestParam(defaultValue = "10") int size) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            return "redirect:/login";
        }
        User user = userOpt.get();
        
        // 只有管理员可以访问
        if (!"ADMIN".equals(user.getRole().name())) {
            return "redirect:/articles";
        }
        
        try {
            Pageable pageable = PageRequest.of(page, size);
            // 获取所有文章，不过滤状态
            Page<Article> allArticles = articleService.getAllArticles(pageable);
            
            // 添加调试信息
            System.out.println("=== 管理员文章页面调试信息 ===");
            System.out.println("文章总数: " + allArticles.getTotalElements());
            System.out.println("当前页文章数: " + allArticles.getContent().size());
            if (!allArticles.getContent().isEmpty()) {
                System.out.println("第一篇文章: " + allArticles.getContent().get(0).getTitle());
                System.out.println("第一篇文章状态: " + allArticles.getContent().get(0).getStatus());
            }
            System.out.println("==============================");
            
            model.addAttribute("articles", allArticles);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", allArticles.getTotalPages());
            model.addAttribute("totalElements", allArticles.getTotalElements());
            
            return "admin-articles";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取文章列表失败：" + e.getMessage());
            return "admin-articles";
        }
    }

    @GetMapping("/articles/{id}/delete")
    public String deleteArticle(@PathVariable Long id, Authentication authentication) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        String username = authentication.getName();
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            return "redirect:/login";
        }
        User user = userOpt.get();
        
        Article article = articleService.getArticleById(id);
        if (article != null && article.getAuthor().equals(user)) {
            articleService.deleteArticle(id);
        }
        
        return "redirect:/articles";
    }
    
    @GetMapping("/categories")
    public String categories(Authentication authentication, Model model) {
        // 获取所有分类
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        
        // 添加用户认证状态
        model.addAttribute("isAuthenticated", authentication != null);
        
        return "categories";
    }
    
    @PostMapping("/categories/create")
    public String createCategory(@RequestParam String name,
                               @RequestParam(required = false) String icon,
                               @RequestParam(required = false) String description,
                               @RequestParam(defaultValue = "true") boolean enabled,
                               Authentication authentication,
                               Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        try {
            Category category = new Category();
            category.setName(name);
            category.setIcon(icon != null ? icon : "📁");
            category.setDescription(description);
            category.setEnabled(enabled);
            
            categoryService.createCategory(category);
            model.addAttribute("message", "分类创建成功！");
        } catch (Exception e) {
            model.addAttribute("error", "分类创建失败：" + e.getMessage());
        }
        
        return "redirect:/categories";
    }
    
    @GetMapping("/categories/{id}/details")
    @ResponseBody
    public Category getCategoryDetails(@PathVariable Long id, Authentication authentication) {
        if (authentication == null) {
            throw new RuntimeException("未登录");
        }
        
        return categoryService.getCategoryById(id);
    }
    
    @PostMapping("/categories/{id}/update")
    public String updateCategory(@PathVariable Long id,
                               @RequestParam String name,
                               @RequestParam(required = false) String icon,
                               @RequestParam(required = false) String description,
                               @RequestParam(defaultValue = "true") boolean enabled,
                               Authentication authentication,
                               Model model) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        try {
            Category category = categoryService.getCategoryById(id);
            if (category != null) {
                category.setName(name);
                category.setIcon(icon != null ? icon : "📁");
                category.setDescription(description);
                category.setEnabled(enabled);
                
                categoryService.updateCategory(category);
                model.addAttribute("message", "分类更新成功！");
            } else {
                model.addAttribute("error", "分类不存在！");
            }
        } catch (Exception e) {
            model.addAttribute("error", "分类更新失败：" + e.getMessage());
        }
        
        return "redirect:/categories";
    }
    
    @GetMapping("/categories/{id}/delete")
    public String deleteCategory(@PathVariable Long id, Authentication authentication) {
        if (authentication == null) {
            return "redirect:/login";
        }
        
        try {
            categoryService.deleteCategory(id);
        } catch (Exception e) {
            // 删除失败，可以添加错误处理
        }
        
        return "redirect:/categories";
    }
    
    @PostMapping("/register")
public String registerUser(@RequestParam String username,
                          @RequestParam String email,
                          @RequestParam String password,
                          @RequestParam String confirmPassword,
                          @RequestParam(required = false) String nickname,
                          @RequestParam(required = false) String bio,
                          Model model) {
    try {
        // 验证密码确认
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password);
        if (nickname != null && !nickname.trim().isEmpty()) {
            user.setNickname(nickname.trim());
        }
        if (bio != null && !bio.trim().isEmpty()) {
            user.setBio(bio.trim());
        }
        
        // 注册用户
        userService.register(user);
        
        model.addAttribute("success", "注册成功！请登录");
        return "login";
    } catch (Exception e) {
        model.addAttribute("error", e.getMessage());
        return "register";
    }
}
}